<template>
  <div class="process-start">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>发起流程 - {{ processDefinition?.name }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        v-loading="loading"
      >
        <template v-for="field in formFields" :key="field.fieldId">
          <!-- 文本输入框 -->
          <el-form-item
            v-if="field.type === 'string'"
            :label="field.label"
            :prop="field.fieldId"
            :rules="getFieldRules(field)"
          >
            <el-input
              v-model="formData[field.fieldId]"
              :placeholder="'请输入' + field.label"
            />
          </el-form-item>

          <!-- 数字输入框 -->
          <el-form-item
            v-else-if="field.type === 'number'"
            :label="field.label"
            :prop="field.fieldId"
            :rules="getFieldRules(field)"
          >
            <el-input-number
              v-model="formData[field.fieldId]"
              :placeholder="'请输入' + field.label"
              :precision="2"
              :step="1"
            />
          </el-form-item>

          <!-- 日期选择器 -->
          <el-form-item
            v-else-if="field.type === 'date'"
            :label="field.label"
            :prop="field.fieldId"
            :rules="getFieldRules(field)"
          >
            <el-date-picker
              v-model="formData[field.fieldId]"
              type="date"
              :placeholder="'请选择' + field.label"
            />
          </el-form-item>

          <!-- 用户选择器 -->
          <el-form-item
            v-else-if="field.type === 'user'"
            :label="field.label"
            :prop="field.fieldId"
            :rules="getFieldRules(field)"
          >
            <el-select
              v-model="formData[field.fieldId]"
              :placeholder="'请选择' + field.label"
              filterable
              remote
              :remote-method="queryUsers"
              :loading="userSelectLoading"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            提交
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const userSelectLoading = ref(false)
const processDefinition = ref(null)
const formFields = ref([])
const formData = ref({})
const formRules = ref({})
const userOptions = ref([])

// 加载流程定义和表单配置
const loadProcessDefinition = async () => {
  loading.value = true
  try {
    const processKey = route.params.processKey
    if (!processKey) {
      throw new Error('流程标识不能为空')
    }

    // 加载流程定义信息
    const defResponse = await request.get('/process-definitions/latest', {
      params: { key: processKey }
    })
    
    if (defResponse.data) {
      processDefinition.value = defResponse.data
    } else {
      throw new Error('流程定义不存在')
    }

    // 加载表单配置
    const formResponse = await request.get(`/form-definitions/${processKey}`)
    if (formResponse.data && formResponse.data.formSchema) {
      try {
        formFields.value = JSON.parse(formResponse.data.formSchema)
        initFormData()
        initFormRules()
      } catch (e) {
        console.error('解析表单配置失败:', e)
        ElMessage.error('表单配置格式错误')
      }
    }
  } catch (error) {
    console.error('加载流程定义失败:', error)
    ElMessage.error(error.message || '加载流程定义失败')
    router.push('/process/definitions')
  } finally {
    loading.value = false
  }
}

// 初始化表单数据
const initFormData = () => {
  const data = {}
  formFields.value.forEach(field => {
    data[field.fieldId] = null
  })
  formData.value = data
}

// 初始化表单验证规则
const initFormRules = () => {
  const rules = {}
  formFields.value.forEach(field => {
    rules[field.fieldId] = getFieldRules(field)
  })
  formRules.value = rules
}

// 获取字段验证规则
const getFieldRules = (field) => {
  const rules = []
  if (field.required) {
    rules.push({
      required: true,
      message: `请${field.type === 'date' ? '选择' : '输入'}${field.label}`,
      trigger: field.type === 'date' ? 'change' : 'blur'
    })
  }
  return rules
}

// 查询用户
const queryUsers = async (query) => {
  if (query) {
    userSelectLoading.value = true
    try {
      const response = await request.get('/users/search', {
        params: { keyword: query }
      })
      userOptions.value = response.data
    } catch (error) {
      console.error('查询用户失败:', error)
    } finally {
      userSelectLoading.value = false
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    await request.post('/process/start', {
      processDefinitionId: processDefinition.value.id,
      variables: formData.value
    })
    
    ElMessage.success('流程发起成功')
    router.push('/process/my-requests')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.response?.data?.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

onMounted(() => {
  loadProcessDefinition()
})
</script>

<style scoped>
.process-start {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form {
  max-width: 600px;
  margin: 0 auto;
}
</style> 